package net.projects.pro3_xunlei;



import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
import java.util.logging.Logger;

public class DownLoadTask implements Runnable {

    private String url;
    private long startPos;

    private long endPos;
    private String downloadPath;

    private DownLoadSizeNotify dlsn;
    final Lock lock=new ReentrantLock();
    Logger log=Logger.getLogger(DownLoadTask.class.getName());
    private CountDownLatch latch;

    public DownLoadTask(String url, long startPos, long endPos, String downloadPath, DownLoadSizeNotify dlsn, CountDownLatch latch) {
        this.url = url;
        this.startPos = startPos;
        this.endPos = endPos;
        this.downloadPath = downloadPath;
        this.dlsn=dlsn;
        this.latch=latch;
    }

    @Override
    public void run() {

        try {
                URL url = new URL(this.url);
                HttpURLConnection conn = (HttpURLConnection) url.openConnection();
                conn.setRequestMethod("GET");
                conn.setRequestProperty("Range", "bytes=" + this.startPos + "-" + this.endPos);
                conn.setConnectTimeout(3000);

                BufferedInputStream bis=new BufferedInputStream(conn.getInputStream()) ;
                RandomAccessFile raf=new RandomAccessFile(this.downloadPath,"rw");
                byte[] bytes=new byte[10*1024*1024];
                int len=0;
                while ((len=bis.read(bytes,0,bytes.length))!=-1){
                    raf.write(bytes,0,len);
                    if (dlsn!=null){
                        dlsn.notifySize(len);
                    }
                }


//            log.info("第" + Thread.currentThread().getName() + "个线程的下载范围为" + startPos + "-" + endPos);
//            log.info("第" + Thread.currentThread().getName() + "个线程下载完成");
            latch.countDown();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
    }
